<script setup lang="ts">
import Write from './Writeed.vue'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { ref, unref } from 'vue'
import { modifyApi } from '@/api/product/list'
import { ElMessage } from 'element-plus'
const emit = defineEmits(['close', 'get-list'])

const writeRef = ref<ComponentRef<typeof Write>>()

const loading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    if (formData.spec_type == 1) {
      const fromList = {
        id: formData.id,
        goods_cate_id_one: formData.goods_cate_id_one,
        goods_cate_id_two: formData.goods_cate_id_two,
        descriptions: formData.descriptions,
        platform_rate: formData.platform_rate,
        company_rate: formData.company_rate,
        driver_rate: formData.driver_rate,
        specs: [
          {
            id: formData.goods_id,
            money: formData.money
          }
        ]
      }
      loading.value = true
      const res = await modifyApi(fromList)
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
      if (res) {
        ElMessage.success(res.msg)
        write?.reset()
        emit('close')
        emit('get-list')
      }
    } else {
      const fromList = {
        id: formData.id,
        goods_cate_id_one: formData.goods_cate_id_one,
        goods_cate_id_two: formData.goods_cate_id_two,
        descriptions: formData.descriptions,
        specs: formData.specs,
        platform_rate: formData.platform_rate,
        company_rate: formData.company_rate,
        driver_rate: formData.driver_rate
      }
      loading.value = true
      const res = await modifyApi(fromList)
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
      if (res) {
        ElMessage.success(res.msg)
        write?.reset()
        emit('close')
        emit('get-list')
      }
    }
  }
}
</script>

<template>
  <ContentDetailWrap title="编辑商品">
    <Write ref="writeRef" />

    <template #footer>
      <div class="w-full flex items-center justify-center">
        <BaseButton type="primary" :loading="loading" @click="save">保存</BaseButton>
        <BaseButton @click="emit('close')">取消</BaseButton>
      </div>
    </template>
  </ContentDetailWrap>
</template>
